/*
 * Copyright 2009 Cedric Priscal
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

package com.vanzo.talkie2;

import android.util.Log;

import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.security.InvalidParameterException;

import android_serialport_api.SerialPort;

public class Application extends android.app.Application {

    private SerialPort mSerialPort = null;
    private String DEFAULT_PROT = "/dev/ttyMT0";
    private static final String TAG = "Application";
    private static final boolean userIO = true;
    private static final String TALKIE_STATE_PATH = "sys/devices/platform/talkie@0/talkieenablestatus";

    public SerialPort getSerialPort(String devicePath, int mBaudrate) throws SecurityException, IOException, InvalidParameterException {
        if (mSerialPort == null) {
            /* Read serial port parameters */
//            SharedPreferences sp = getSharedPreferences("android_serialport_api.sample_preferences", MODE_PRIVATE);
//			String path = sp.getString("DEVICE", "");
//			int baudrate = Integer.decode(sp.getString("BAUDRATE", "-1"));
            String path;
            if (devicePath == null) {
                path = "/dev/ttyMT0";
            } else {
                path = devicePath;
            }
            int baudrate = mBaudrate;

			/* Check parameters */
            if ((path.length() == 0) || (baudrate == -1)) {
                throw new InvalidParameterException();
            }

			/* Open the serial port */
            mSerialPort = new SerialPort(new File(path), baudrate, 0);
        }
        return mSerialPort;
    }

    public SerialPort getSerialPort() throws SecurityException, IOException, InvalidParameterException {
        return getSerialPort(DEFAULT_PROT, 9600);
    }

    public void init() throws IOException {
        getSerialPort();
    }

    public void closeSerialPort() {
        if (mSerialPort != null) {
            mSerialPort.close();
            mSerialPort = null;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
//        setChargeNode(TALKIE_STATE_PATH, "1");
//        setTalkie("1");
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
//        setChargeNode(TALKIE_STATE_PATH, "0");
//        setTalkie("0");
        closeSerialPort();
    }

    private void setChargeNode(String path, String node) {
        if (userIO) {
            setChargeNodeByIO(path, node);
        } else {
            Process p = null;
            DataOutputStream os = null;
            try {
                p = Runtime.getRuntime().exec("sh");
                os = new DataOutputStream(p.getOutputStream());
                os.writeBytes("echo " + node + " > " + path + "\n");
                os.writeBytes("exit\n");
                os.flush();
                Log.e(TAG, " write successful talkie = " + node);
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, " can't write " + path + " " + e.getMessage());
            } finally {
                if (p != null) {
                    p.destroy();
                }
                if (os != null) {
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    private void setTalkie(String status) {
        try {

            Process p = Runtime.getRuntime().exec("echo " + status + " > " + TALKIE_STATE_PATH);
            int result = p.waitFor();
            if (result == 0) {
                Log.d(TAG, " write successful talkie = " + status);
            } else {
                Log.d(TAG, " failed to write successful talkie = " + status);
            }
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, " can't write " + TALKIE_STATE_PATH + " " + e.getMessage());
        }

    }

    private void setChargeNodeByIO(String path, String node) {
        try {
            BufferedWriter bufWriter = null;
            bufWriter = new BufferedWriter(new FileWriter(path));
            bufWriter.write(node);  // 写操作
            bufWriter.close();
            Log.d(TAG, " write successful talkie = " + node + " by IO");
        } catch (IOException e) {
            e.printStackTrace();
            Log.e(TAG, " can't write " + path + e.getMessage());
        }
    }
}
